package com.sanpu.kxe.business.login.presenter;

import android.app.Activity;
import android.util.Log;

import com.sanpu.kxe.business.login.contract.LoginConfig;
import com.sanpu.kxe.business.login.contract.SetPasswordContract;
import com.sanpu.kxe.business.login.model.LoginModel;
import com.sanpu.kxe.business.login.view.LoginActivity;
import com.sanpu.kxe.business.main.bean.UserCenterOutput;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.utils.AppContextUtil;
import com.sanpu.kxe.utils.IntentTool;
import com.sanpu.kxe.utils.ToastUtil;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：密码相关
 * Created by 薛勇军 on 2018/6/25.
 */

public class SetPasswordPresenter implements SetPasswordContract.Presenter {

    private SetPasswordContract.View mView;

    /** 账户名称 */
    private String accountName;

    /** 验证码类型 */
    private String mSmsType;

    /** 密码类型 */
    private String pwdType;

    private CompositeSubscription mSubscription;

    public SetPasswordPresenter(SetPasswordContract.View mView) {
        this.mView = mView;
        mSubscription = new CompositeSubscription();
        UserCenterOutput userCenterOutput = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
        if (userCenterOutput != null) {
            accountName = userCenterOutput.getUserName();
        }
    }

    @Override
    public void initType(String pwdType) {
        this.pwdType = pwdType;
        switch (pwdType) {
            case LoginConfig.UPDATE_PWD:
                mSmsType = CommonConfig.SMSTYPE_UPDPWD;
                mView.resetPwdView(accountName);
                break;
            case LoginConfig.FORGET_PWD:
                mSmsType = CommonConfig.SMSTYPE_UPDPWD;
                mView.forgetPwdView(accountName);
                break;
            case LoginConfig.PAY_PWD:
                mSmsType = CommonConfig.SMSTYPE_UPDPAYPWD;
                mView.payPwdView(accountName);
                break;
            default:
                return;
        }
    }

    @Override
    public void sendCode(final String phoneNumber) {
        Observable.interval(0, 1, TimeUnit.SECONDS)//设置0延迟，每隔一秒发送一条数据
                .take(CommonConfig.SMS_SEC + 1) //设置循环11次
                .map(new Func1<Long, Long>() {
                    @Override
                    public Long call(Long aLong) {
                        return CommonConfig.SMS_SEC - aLong;
                    }
                })
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        mView.changeByStatus(true);
                        Subscription subscription = LoginModel.getInstance()
                                .sendSms(phoneNumber, mSmsType)
                                .subscribeOn(Schedulers.io())
                                .unsubscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Observer<String>() {
                                    @Override
                                    public void onCompleted() {

                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        mView.dismissLoadingDialog();
                                        mView.showErrorText(e);
                                    }

                                    @Override
                                    public void onNext(String s) {
                                        ToastUtil.showTextViewPromptShort("验证码发送成功！");
                                    }
                                });
                        mSubscription.add(subscription);
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onCompleted() {
                        Log.e("SetPassword", "onCompleted: ");
                        mView.changeByStatus(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(Long aLong) { //接受到一条就是会操作一次UI
                        Log.e("SetPassword", "onNext: " + aLong);
                        mView.byoyomi(aLong);
                    }
                });
    }

    @Override
    public void onNextClick(String accountName, String password, String smsCode) {
        switch (pwdType) {
            case LoginConfig.UPDATE_PWD:
                updateLoginPassword(password, smsCode);
                break;
            case LoginConfig.FORGET_PWD:
                forgetPassword(accountName, password, smsCode);
                break;
            case LoginConfig.PAY_PWD:
                updatePayPassword(accountName, password, smsCode);
                break;
            default:
                return;
        }
    }

    /**
     * 设置密码
     */
    private void updateLoginPassword(String password, String smsCode) {
        mView.showLoadingDialog(false);
        Subscription subscription = LoginModel.getInstance().updateLoginPwd(password, smsCode)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(String s) {
                        ToastUtil.showTextViewPrompt("密码修改成功，请重新登录！");
                        AppContextUtil.exit(mView.getContext());
                    }
                });
        mSubscription.add(subscription);
    }

    /**
     * 设置支付密码
     */
    private void updatePayPassword(String accountName, String password, String smsCode) {
        mView.showLoadingDialog(false);
        Subscription subscription = LoginModel.getInstance()
                .updatePayPwd(accountName, password, smsCode)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(String s) {
                        ToastUtil.showTextViewPrompt("修改支付密码成功！");
                        ((Activity)mView.getContext()).finish();
                    }
                });
        mSubscription.add(subscription);
    }

    /**
     * 忘记密码
     */
    private void forgetPassword(String accountName, String password, String smsCode) {
        mView.showLoadingDialog(false);
        Subscription subscription = LoginModel.getInstance()
                .forgetPassword(accountName, password, smsCode)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(String s) {
                        ToastUtil.showTextViewPrompt("密码修改成功！");
                        IntentTool.startActivity(mView.getContext(), LoginActivity.class);
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void onDestroyPresenter() {
        if (mView != null)
            mView = null;
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
    }
}
